package session1.practises.whatIsIt;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class MyThread extends Thread {
    static int ticket = 0;
    static Lock lock = new ReentrantLock();
    static int totalTickets;
    static int number;
    static CountDownLatch latch;
    public static void setTotalTickets(int totalTickets) {
        MyThread.totalTickets = totalTickets;
    }
    public static void setNumber(int number) {
        MyThread.number = number;
    }
    public
//    static
    void setLatch(CountDownLatch latch) {
        MyThread.latch = latch;
    }
    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (ticket < totalTickets) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ticket++;
                System.out.println(getName() + "抢到了第" + ticket + "张票");
            } else {
                lock.unlock();
                break;
            }
            lock.unlock();
        }
        latch.countDown();
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入初始票的数量：");
        int totalTickets = scanner.nextInt();
        System.out.print("请输入抢票人数：");
        int number = scanner.nextInt();
        MyThread.setTotalTickets(totalTickets);
        MyThread.setNumber(number);
        CountDownLatch latch = new CountDownLatch(number);
        for (int i = 1; i <= number; i++) {
            MyThread thread = new MyThread();
            thread.setName(i + "号观众:");
            thread.setLatch(latch);
            thread.start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.print("请输入补票数量：");
        int extraTickets = scanner.nextInt();
        if(extraTickets<=0)
            return;
        MyThread.setTotalTickets(totalTickets + extraTickets);
        for (int i = 1; i <= extraTickets; i++) {
            MyThread thread = new MyThread();
            thread.setName("(补票)观众" + i + ":");
            thread.start();
        }
    }
}